package com.ywh.composetest.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.sp
import com.ywh.composetest.ui.theme.ComposeTestTheme

val LocalName = compositionLocalOf { "name-init" }

class CompositionLocalProviderTestActivity : ComponentActivity() {
    private val TAG = CompositionLocalProviderTestActivity::class.java.simpleName
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            //LocalName在CompositionLocalProvider作用域内获取的是修改后的值 name-ywh-main，函数体外获取的是 name123
            CompositionLocalProvider(LocalName provides "name-provides") {
                Log.e(TAG, "作用域内1:${LocalName.current}")
                ComposeTestTheme {
                    Log.e(TAG, "作用域内2:${LocalName.current}")
                    // A surface container using the 'background' color from the theme
                    Scaffold(
                        modifier = Modifier.fillMaxSize()
                    ) { _ ->
                        Log.e(TAG, "作用域内3:${LocalName.current}")
                        LocalName provides "name new"
                        Log.e(TAG, "作用域内 provides不会生效:${LocalName.current}")

                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = "CompositionLocalProvider + staticCompositionLocalOf、CompositionLocalOf\n\n" +
                                        "CompositionLocalProvider提供作用域，修改的值只在作用域内有效\n\n" +
                                        "CompositionLocalOf:值改变时，只有compositionLocalProvider作用域下使用current值的组件重组\n\n" +
                                        "staticCompositionLocalOf:值改变时，compositionLocalProvider作用域下全重组，所以staticCompositionLocalOf适用于常量，不改变的值",
                                fontSize = 13.sp
                            )
                        }
                    }
                }
            }
            Log.e(TAG, "作用域之外:${LocalName.current}")
        }
    }
}